package com.ruyuan.seckilling.activity.controller;

import com.ruyuan.seckilling.activity.request.ActivitySaveRequest;
import com.ruyuan.seckilling.activity.request.ActivitySkuRefSaveRequest;
import com.ruyuan.seckilling.common.MapResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 测试使用
 */
@Slf4j
@RestController
@RequestMapping("/activity/test")
public class TestController {

    @Autowired
    private ActivityController activityController;

    @Autowired
    private ActivitySkuRefController activitySkuRefController;

    // curl http://localhost:7001/test/step1
    @GetMapping("/step1")
    public void test1() {

        Date now = new Date();

        Date showTime = DateUtils.addSeconds(now, 30);
        Date startTime = DateUtils.addMinutes(now, 1);
        Date endTime = DateUtils.addMinutes(now, 30);

        FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
        String activityName = "测试秒杀活动" + dateFormat.format(startTime) + "开始";


        // 1. 根据当前时间添加一个活动
        ActivitySaveRequest activitySaveRequest = ActivitySaveRequest.builder()
                .activityName(activityName)
                .showTime(showTime)
                .startTime(startTime)
                .endTime(endTime)
                .build();
        MapResult mapResult = activityController.save(activitySaveRequest);
        Long activityId = (Long) mapResult.get("id");
        log.info("保存秒杀活动，活动id={}", activityId);

        // 2. 给活动添加商品(10个商品，每个库存10)
        Long activitySkuRefId = 0L;
        for (int i = 1; i <= 10; i++) {
            ActivitySkuRefSaveRequest activitySkuRefSaveRequest = ActivitySkuRefSaveRequest.builder()
                    .activityId(activityId)
                    .skuId(Long.parseLong(i + ""))
                    .price(500)
                    .seckillingStock(10)
                    .build();
            mapResult = activitySkuRefController.save(activitySkuRefSaveRequest);
            activitySkuRefId = (Long) mapResult.get("id");
            log.info("添加秒杀商品，记录id={}, 活动id={}, 商品id={}, 库存数量={}", activitySkuRefId, activityId, i, 10);
        }

        // 3. 提交审核
        activityController.submit(activityId);
        log.info("提交审核，活动id={}", activityId);

        // 4. 审核通过
        activityController.audit(activityId, true);
        log.info("审核通过，活动id={}", activityId);

        // 5. 后面定时任务就开始跑了
    }
}
